package com.xubaohua.JUC并发包.juc三大辅助类;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * @program: JavaSenior
 * @description:
 * @author: 许宝华
 * @create: 2022-07-05 15:39
 */


public class SemaphoreTest {
    public static void main(String[] args) {

        Semaphore semaphore=new Semaphore(3);//三个空车位
        for (int i = 0; i <7; i++) { //七个车抢资源
            new Thread(()->{
                try {
                    semaphore.acquire();
                    System.out.println(Thread.currentThread().getName()+"抢到了车位");
                    try {
                        TimeUnit.SECONDS.sleep(3);
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName()+"离开了车位");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }finally {
                    semaphore.release();
                }
            },String.valueOf(i)).start();
        }

    }
}
